#define WIN32_LEAN_AND_MEAN
#include "Protos.h"
PVOID MakeCodeCaveInDll(__in PUNICODE_STRING DllName,__in size_t bSize)
{
	PLDR_MODULE LdrInfo = {0};
	OBJECT_NAME_INFORMATION ObName = {0};
	SECTION_BASIC_INFORMATION sbInfo = {0};
	LARGE_INTEGER SecNewSize = {0};
	OBJECT_ATTRIBUTES oa = {0};
	HANDLE hTargetSection = INVALID_HANDLE_VALUE;
	NTSTATUS Status = 0;
	void* hMod = 0;
	ULONG Result = 0;
	__try
	{
		//you can use GetModuleHandle here..I like mine.
		if( NT_SUCCESS(LdrLoadDll(0,0,DllName,&hMod)))
		{
			Status = LdrFindEntryForAddress(hMod,&LdrInfo);
			if(!NT_SUCCESS(Status))
			{
				__leave;
			}
			if(wcscmp((wchar_t*)LdrInfo->BaseDllName.Buffer,DllName->Buffer) == 0)
			{
				Status = NtQueryObject(LdrInfo->BaseAddress,ObjectNameInformation,&ObName,sizeof(OBJECT_NAME_INFORMATION),&Result);
				if(!NT_SUCCESS(Status))
				{
					__leave;
				}
				InitializeObjectAttributes(&oa,&ObName.Name,OBJ_OPENIF,0,0);
				Status = NtOpenSection(&hTargetSection,SECTION_EXTEND_SIZE,&oa);
				if(!NT_SUCCESS(Status))
				{
					__leave;
				}
				Status = NtQuerySection(hTargetSection,SectionBasicInformation,&sbInfo,sizeof(SECTION_BASIC_INFORMATION),&Result);
				if(!NT_SUCCESS(Status))
				{
					__leave;
				}
				SecNewSize.LowPart =(sbInfo.Size.LowPart + (DWORD)bSize);
				Status = NtExtendSection(hTargetSection,&SecNewSize);
				if(!NT_SUCCESS(Status))
				{
					__leave;
				}
				return (PVOID)((ULONG)hMod + sbInfo.Size.LowPart);
			}
		}
		return 0;
	}
	__except(1)
	{
		if(hTargetSection != INVALID_HANDLE_VALUE)
			NtClose(hTargetSection);
	}
	return 0;
}



